package com.bjsxt.redis.conf;

import org.springframework.cache.CacheManager;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @ClassName : RedisConf
 * @Description :定义一个父类型，用于提供模板配置
 * @Author : ZWZ
 * @Date: 2021/8/26 10:05
 */
public abstract class RedisCacheConfiguration {


    /**
     * key 序列化器
     */
    protected final StringRedisSerializer STRING_REDIS_SERIALIZER = new StringRedisSerializer();
    /**
     * value 序列化器
     */
    protected final GenericJackson2JsonRedisSerializer GENERIC_JACKSON_2_JSON_REDIS_SERIALIZER
            = new GenericJackson2JsonRedisSerializer();

    /**
     * 缓存管理
     * 设置 @cacheable 注解的序列化
     *
     * @param
     * @return
     */
    protected CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        org.springframework.data.redis.cache.RedisCacheConfiguration configuration =
                org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig();
        // 注意配置 RedisCacheConfiguration 类需要新创建一个变量来接收， 否则配置不生效
        org.springframework.data.redis.cache.RedisCacheConfiguration redisCacheConfiguration = configuration
                // 默认超时时间
                .entryTtl(Duration.ofMinutes(30L))
                // key 序列化器
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(STRING_REDIS_SERIALIZER))
                // value 序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(GENERIC_JACKSON_2_JSON_REDIS_SERIALIZER))
                // 不缓存空数据
                .disableCachingNullValues();
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration)
                .build();
    }

    /**
     * 操作 redis
     *
     * @param redisConnectionFactory
     * @return
     */
    protected RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(STRING_REDIS_SERIALIZER);
        redisTemplate.setValueSerializer(GENERIC_JACKSON_2_JSON_REDIS_SERIALIZER);
        return redisTemplate;
    }

}
